package com.binance.rabbitmq.config;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

/**
 * Created by robin.wu on 2018/11/29.
 */
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Log4j2
@ConfigurationProperties
public class DeadLetterConfig extends AbstractConfig {
    /** 如果某个queue enable了死信队列，则死信队列的名称默认为 原队列.DLQ **/
    private static final String DEFAULT_DEAD_LETTER_QUEUE_POSTFIX = ".DLQ";

    @NestedConfigurationProperty
    private ExchangeConfig deadLetterExchange;

    private Integer threshold;

    /**
     * postfix for the dead  letter queue name
     */
    @Builder.Default
    private String queuePostfix = DEFAULT_DEAD_LETTER_QUEUE_POSTFIX;

    public String createDeadLetterQueueName(String queueName) {
        return new StringBuilder()
                .append(queueName)
                .append(getDefaultConfig("DeadLetterConfig", "queuePostfix", queuePostfix, null, DEFAULT_DEAD_LETTER_QUEUE_POSTFIX)).toString();
    }

    @Override
    public boolean validate() {
        log.info("Validating DeadLetterConfig...");
        if (deadLetterExchange != null && deadLetterExchange.validate()) {
            log.info("DeadLetterConfig configuration validated successfully for deadLetterExchange '{}'", deadLetterExchange);
            return true;
        }
        log.error("Invalid DeadLetterConfig Configuration : Valid DeadLetterExchange must be provided for DeadLetterConfig");
        return false;
    }
}
